const crypto = require('crypto');

// 加密方法（返回hex格式字符串）
function encrypt(password, secretKey = 'tuisa') {
    const key = crypto.scryptSync(secretKey, 'salt', 32); // 生成32字节密钥
    const iv = crypto.randomBytes(16); // 生成16字节随机初始化向量

    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(password, 'utf8', 'hex');
    encrypted += cipher.final('hex');

    return `${iv.toString('hex')}:${encrypted}`; // 返回IV+密文组合
}

// 解密方法
function decrypt(encryptedText, secretKey = 'tuisa') {
    const [ivHex, encrypted] = encryptedText.split(':');
    const key = crypto.scryptSync(secretKey, 'salt', 32);
    const iv = Buffer.from(ivHex, 'hex');

    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');

    return decrypted;
}

module.exports = { encrypt, decrypt };
